import re, traceback,subprocess
from libs.mypthon.textToAss import textToass_file
from libs.mypthon import DEFINE
from pygoogletranslation import Translator


# 四六级视频添加选项
def English_4_and_6_options_subtitle_production(optionsText, asstextfile, arg_dict, saveAssfilename):
    try:
        # 获取选项片段列表
        # 去除Section....部分,保留选项
        pattern = re.compile('Section.+?Questions', re.DOTALL)
        while True:
            result = re.search(pattern, optionsText)
            if result != None:
                string = result.group()
                # print(string)
                string = string.replace('Questions', '')
                optionsText = optionsText.replace(string, '')
            else:
                break
        # print(optionsText)
        # 分开
        textList = optionsText.split('Questions')
        # print((textList))
        '''
        ['',
         ' 1 to 4 are based on the conversation you have just heard.\n1. A) A six- month-long negotiation.\tB) Preparations for the party.\n\tC) A project with a troublesome client.\tD) Gift wrapping for the colleagues.\n2. A) Take wedding photos.\tB) Advertise her company.\n\tC) Start a small business.\tD) Throw a celebration party.\n3. A) Hesitant.\tB) Nervous.\n\tC) Flattered.\tD) Surprised.\n4. A) Start her own bakery.\tB) Improve her baking skill.\n\tC) Share her cooking experience.\tD) Prepare food for the wedding.\n',
         ' 5 to 8 are based on the conversation you have just heard.\n5. A) They have to spend more time studying.\n\tB) They have to participate in club activities.\n\tC) They have to be more responsible for what they do.\n\tD) They have to choose a specific academic discipline.\n6. A) Get ready for a career.\tB) Make a lot of friends.\n\tC) Set a long-term goal.\tD) Behave like adults.\n7. A) Those who share her academic interests.\t\n\tB) Those who respect her student commitments.\n\tC) Those who can help her when she is in need.\n\tD) Those who go to the same clubs as she does.\n8. A) Those helpful for tapping their potential.\n\tB)Those conducive to improving their social skills.\n\tC)Those helpful for cultivating individual interests.\n\tD)Those conducive to their academic studies.\n',
         ' 9 to 11 are based on the passage you have just heard.\n9.A) They break away from traditional ways of thinking.\n\tB) They are prepared to work harder than anyone else.\n\tC) They are good at refining old formulas.\n\tD) They bring their potential into full play.\n10. A) They contributed to the popularity of skiing worldwide.\n\tB) They resulted in a brandnew style of skiing techniques.\n\tC) They promoted the scientific use of skiing poles.\n\tD) They made explosive news in the sports world.\n11. A) He was recognized as a genius in the world of sports.\n\tB)He competed in all major skiing events in the world.\n\tC)He won three gold medals in one Winter Olympics.\n\tD)He broke three world skiing records in three years.\n',
         ' 12 to 15 are based on the passage you have just heard.\n12. A) They appear restless.\tB) They lose consciousness.\n\tC) They become upset.\tD) They die almost instantly.\n13. A) It has an instant effect on your body chemistry.\n\tB)It keeps returning to you every now and then.\n\tC)It leaves you with a long-lasting impression.\n\tD)It contributes to the shaping of you mind.\n14. A) To succeed while feeling irritated.\tB) To feel happy without good health.\n\tC) To be free from frustration and failure.\tD) To enjoy good health while in dark moods.\n15. A) They are closely connected.\tB) They function in a similar way.\n\tC) They are too complex to understand.\tD) They reinforce each other constantly.\n',
         ' 16 to 18 are based on the recording you have just heard.\n16. A) They differ in their appreciation of music.\n\tB) They focus their attention on different things.\n\tC) They finger the piano keys in different ways.\n\tD) They choose different pieces of music to play.\n17. A) They manage to cooperate well with their teammates.\n\tB) They use effective tactics to defeat their competitors.\n\tC) They try hard to meet the spectators’ expectations.\n\tD) They attach great importance to high performance.\n18. A) It marks a breakthrough in behavioral science.\n\tB) It adopts a conventional approach to research.\n\tC) It supports a piece of conventional wisdom.\n\tD) It gives rise to controversy among experts.\n',
         ' 19 to 21 are based on the recording you have just heard.\n19. A) People’s envy of slim models.\tB) People’s craze for good health.\n\tC) The increasing range of fancy products.\tD) The great variety of slimming products.\n20. A) They appear vigorous.\tB) They appear strange.\n\tC)They look charming.\tD) They look unhealthy.\n21.A) Culture and upbringing.\tB) Wealth and social status.\n\tC)Peer pressure.\tD) Media influence.\n',
         ' 22 to 25 are based on the recording you have just heard.\n22. A) The relation between hair and skin.\tB) The growing interest in skin studies.\n\tC)The color of human skin.\tD) The need of skin protection.\n23. A) The necessity to save energy.\tB) Adaptation to the hot environment.\n\tC)The need to breathe with ease.\tD)Dramatic climate changes on earth.\n24. A) Leaves and grass.\tB) Man-made shelter.\n\tC)Their skin coloring.\tD) Hair on their skin.\n25.A) Their genetic makeup began to change.\tB)Their communities began to grow steadily.\n\tC)Their children began to mix with each other.\tD)Their pace of evolution began to quicken.']
        '''
        del textList[0]

        # 时间
        with open(asstextfile, 'r') as rfile:
            asslist = list(eval(rfile.read()))
        res_list = []
        bo_have_begin = False
        lasttime = 0
        begintime = 0
        i = 0
        for i_dict in asslist:
            lasttime = (i_dict[DEFINE.KEY_ENDTIME])
            if i == 0:
                begintime = i_dict[DEFINE.KEY_BENGINTIME]
            i = i + 1
            text = i_dict[DEFINE.KEY_TEXT]
            # if ('you have just heard' in text):有时候识别不准
            if ((('base' in text)and(('on'in text)or('in'in text)) and (('are' in text)or('Are'in text)) )):
                # and (('Questions' in text) or ('Question' in text))
                bo_have_begin = True
                begint = (i_dict[DEFINE.KEY_BENGINTIME])
                res_list.append(begint)
            elif bo_have_begin==False:
                if (('You have just'in text)or('you have just'in text)):
                    bo_have_begin = True
                    begint = (i_dict[DEFINE.KEY_BENGINTIME])
                    res_list.append(begint)
            elif ((('Conversation' in text) or ('Section' in text) or (
                    'section' in text) or ('Passage' in text) or ('Reporting' in text) or ('Recording' in text) or (
                          'recording' in text)) and bo_have_begin == True):
                bo_have_begin = False
                endtime = (i_dict[DEFINE.KEY_ENDTIME])
                res_list.append(endtime)

        res_list.append(lasttime)

        # 组合翻译部分
        print(res_list)
        # return
        i = 0
        return_list = []
        for text in textList:
            text = text.replace('\n', '\\N')
            dic = {DEFINE.KEY_BENGINTIME: res_list[i], DEFINE.KEY_ENDTIME: res_list[i + 1], DEFINE.KEY_TEXT: text}
            return_list.append(dic)
            i = i + 2
        else:
            # 按照每一行翻译
            ass_list = []
            for i_dict in return_list:
                text = i_dict[DEFINE.KEY_TEXT]
                li = list(text.split('\\N'))
                transtor = Translator()
                # print('li=',li)
                t = transtor.translate(li, src='en', dest='zh-CN')
                trans_list = []
                for item in t:
                    trans_list.append(item.text)
                trans_text = '\\N'.join(trans_list)
                text = text + '\\N' + trans_text
                ass_list.append({DEFINE.KEY_BENGINTIME: i_dict[DEFINE.KEY_BENGINTIME],
                                 DEFINE.KEY_ENDTIME: i_dict[DEFINE.KEY_ENDTIME], DEFINE.KEY_TEXT: text})
            return_list = ass_list
            # 整段翻译
            '''
            bo_sucess,trans_list=translate(return_list,True,'zh-CN')
            if bo_sucess:
                new_translist=[]
                for i_dict in trans_list:
                    text=i_dict[DEFINE.KEY_TEXT]
                    text=text.replace('\ n','\\N')
                    new_translist.append({DEFINE.KEY_BENGINTIME:i_dict[DEFINE.KEY_BENGINTIME],DEFINE.KEY_ENDTIME:i_dict[DEFINE.KEY_ENDTIME],DEFINE.KEY_TEXT:text})
                return_list=new_translist
            else:
                print('翻译失败')
            '''

            # 组合不翻译部分
            timelist = []
            timelist.append(begintime)
            for i in res_list:
                timelist.append(i)
            # no_trans_asslist=[]
            # print(timelist)
            del timelist[-1]
            # return
            j = 0
            for text in textList:
                text = text.replace('\n', '\\N')
                # 隐藏答案
                answer = re.search('\[.+?]', text)
                if answer != None:
                    ans = answer.group()
                    text = text.replace(ans, '')
                return_list.append({DEFINE.KEY_BENGINTIME: timelist[j] + 1000, DEFINE.KEY_ENDTIME: timelist[j + 1] - 1000,
                                    DEFINE.KEY_TEXT: text})
                j = j + 2

            # 字幕
            textToass_file(return_list, saveAssfilename, arg_dict)
    except Exception as e:
        msg = traceback.format_exc()
        print(msg)
        return False, msg
    else:
        return True, ''

#字幕转换
def swapSubtit(ori_subtit,tar_subtit):
    arg = '-y -i "{}" "{}"'.format(ori_subtit,tar_subtit)
    print(arg)
    ffmpeg_path = DEFINE.DIN_FFMPEG_PATH
    # 创建进程
    ffmpeg = subprocess.Popen('{} {}'.format(ffmpeg_path, arg), shell=True,stdout = subprocess.PIPE, stderr = subprocess.PIPE )
    # stdout = subprocess.PIPE, stderr = subprocess.PIPE
    # 进程id
    id = ffmpeg.pid
    # 阻塞
    out, err = ffmpeg.communicate()
    if str(type(err)) == "<class 'bytes'>":
        arg_str = str(err, 'utf-8')
    else:
        arg_str = str(err)
    print(err)
    retcode = ffmpeg.poll()
    return {DEFINE.KEY_PID: id, DEFINE.KEY_RETCODE: retcode, DEFINE.KEY_OUTINFO: arg_str}

if __name__ == '__main__':
    arg_dict = {DEFINE.KEY_assStyle_Fontname: '宋体',
                DEFINE.KEY_assStyle_Fontsize: 8,
                DEFINE.KEY_assStyle_PrimaryColour: '&H00000000',
                DEFINE.KEY_assStyle_Bold: '',
                DEFINE.KEY_assStyle_Italic: '',
                DEFINE.KEY_assStyle_Underline: '',
                DEFINE.KEY_assStyle_Spacing: '',
                DEFINE.KEY_assStyle_Alignment: 1}

    with open(r'H:/t2.txt', 'r') as rfile:
        s = rfile.read()
        English_4_and_6_options_subtitle_production(s,
                                                    r'D:\myproject\python_project\Application_project\jingting\jingting_tempFiles\Make_video_sequentially\audioToText.txt',
                                                    arg_dict, 'H:/字幕.ass')
